<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
</head>
<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen">等待玩家连接中...</div>
            <!-- 添加棋子颜色显示 -->
            <div id="player_info">棋子颜色：等待分配...</div>
        </div>
        <div id="chat_area" width="400px" height="300px">
            <div id="chat_show">
                <!-- <p id="self_msg">你好！</p></br>
                <p id="peer_msg">你好！</p></br> -->
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>
    <script>
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        //获取chess控件区域2d画布
        let context = chess.getContext('2d');

        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);

        var room_info = null;//用来保存房间信息
        var is_me;//是否该我行动
        var isWhite;//是否是白棋
        var gameOver = false; // 添加游戏结束状态标志

        // 自动滚动到聊天框底部
        function scrollToBottom() {
            var chatShow = document.getElementById("chat_show");
            // 使用requestAnimationFrame确保在DOM更新后执行
            requestAnimationFrame(() => {
                chatShow.scrollTop = chatShow.scrollHeight;
            });
        }

        function initGame() {
            initBoard();
            gameOver = false; // 重置游戏状态
            // 背景图片
            let logo = new Image();
            //logo.src = "image/sky.jpeg";
            logo.src = "http://mihayou666.oss-cn-beijing.aliyuncs.com/img/sky.jpeg";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }
            // 图片加载失败时使用备用背景
            logo.onerror = function() {
                useFallbackBackground();
            };
        }

        function useFallbackBackground() {
            // 使用渐变背景
            var gradient = context.createLinearGradient(0, 0, 450, 450);
            gradient.addColorStop(0, "#E3F2FD");
            gradient.addColorStop(1, "#BBDEFB");
            context.fillStyle = gradient;
            context.fillRect(0, 0, 450, 450);
            drawChessBoard();
        }

        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            context.strokeStyle = "#BFBFBF";
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                //横向的线条
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); 
                context.stroke();
                //纵向的线条
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); 
                context.stroke();
            }
        }
        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            //createLinearGradient() 方法创建放射状/圆形渐变对象
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }

        // 更新玩家信息显示
        function updatePlayerInfo() {
            var playerInfoDiv = document.getElementById("player_info");
            if (room_info && room_info.white_id) {
                var isWhitePlayer = room_info.uid == room_info.white_id;
                var colorText = isWhitePlayer ? "白棋 ⚪" : "黑棋 ⚫";
                var colorClass = isWhitePlayer ? "white-player" : "black-player";
                
                playerInfoDiv.innerHTML = `棋子颜色：<span class="${colorClass}">${colorText}</span>`;
            } else {
                playerInfoDiv.innerHTML = "棋子颜色：等待分配...";
            }
        }

        // 绘制棋子示例（在玩家信息旁边显示小棋子图标）
        function drawPlayerColorExample() {
            var playerInfoDiv = document.getElementById("player_info");
            
            // 创建小canvas显示棋子示例
            var exampleCanvas = document.createElement('canvas');
            exampleCanvas.width = 60;
            exampleCanvas.height = 30;
            var exampleCtx = exampleCanvas.getContext('2d');
            
            if (room_info && room_info.white_id) {
                var isWhitePlayer = room_info.uid == room_info.white_id;
                
                // 绘制白棋示例
                exampleCtx.beginPath();
                exampleCtx.arc(15, 15, 10, 0, 2 * Math.PI);
                var whiteGradient = exampleCtx.createRadialGradient(13, 13, 10, 13, 13, 0);
                whiteGradient.addColorStop(0, "#D1D1D1");
                whiteGradient.addColorStop(1, "#F9F9F9");
                exampleCtx.fillStyle = whiteGradient;
                exampleCtx.fill();
                
                // 绘制黑棋示例
                exampleCtx.beginPath();
                exampleCtx.arc(45, 15, 10, 0, 2 * Math.PI);
                var blackGradient = exampleCtx.createRadialGradient(43, 13, 10, 43, 13, 0);
                blackGradient.addColorStop(0, "#0A0A0A");
                blackGradient.addColorStop(1, "#636766");
                exampleCtx.fillStyle = blackGradient;
                exampleCtx.fill();
                
                // 高亮当前玩家的棋子
                exampleCtx.strokeStyle = isWhitePlayer ? "#FF0000" : "#FF0000";
                exampleCtx.lineWidth = 2;
                exampleCtx.beginPath();
                exampleCtx.arc(isWhitePlayer ? 15 : 45, 15, 12, 0, 2 * Math.PI);
                exampleCtx.stroke();
            }
            
            // 如果已存在示例canvas则替换
            var existingExample = document.getElementById('color_example');
            if (existingExample) {
                playerInfoDiv.removeChild(existingExample);
            }
            exampleCanvas.id = 'color_example';
            playerInfoDiv.appendChild(exampleCanvas);
        }

        //棋盘区域的点击事件
        chess.onclick = function (e) {
            // 如果游戏已经结束，禁止点击棋盘
            if (gameOver) {
                alert("游戏已结束，请点击\"返回大厅\"开始新游戏");
                return;
            }

            //1.获取下棋位置，判断当前下棋操作是否正常
            //当前是否轮到自己走棋了
            //当前位置是否已经被占用

            //如果没有轮到自己走棋，就提示等待对方走棋
            if(!is_me)
            {
                alert("等待对方走棋...");
                return;
            }   

            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            
            // 添加边界检查
            if (row < 0 || row >= BOARD_ROW_AND_COL || col < 0 || col >= BOARD_ROW_AND_COL) {
                return;
            }
            
            if (chessBoard[row][col] != 0) {
                alert("当前位置已有棋子！");
                return;
            }
            //先不要绘制棋子
            //oneStep(col, row, true);

            //2.向服务器发送走棋请求   
            //向服务器发送走棋请求，收到响应后，再绘制棋子
            send_chess(row, col);
        }

        function send_chess(r, c){
            var chess_info = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c
            }
            ws_hdl.send(JSON.stringify(chess_info));
            console.log("click: " + JSON.stringify(chess_info));
        }

        window.onbeforeunload = function(){
            ws_hdl.close();
        }

        ws_hdl.onopen = function(){
            console.log("游戏房间长连接建立成功");
        }

        ws_hdl.onclose = function(){
            console.log("游戏房间长连接断开");
        }

        ws_hdl.onerror = function(){
            console.log("游戏房间长连接出现错误");
        }

        function set_screen(me){
            var screen_div = document.getElementById("screen");
            if(me)
            {
                screen_div.innerHTML = "轮到己方走棋...";
                screen_div.className = "my-turn";
            }
            else 
            {
                screen_div.innerHTML = "轮到对方走棋...";
                screen_div.className = "opponent-turn";
            }
        }

        // 禁用棋盘点击
        function disableChessBoard() {
            chess.style.pointerEvents = "none";
            chess.style.opacity = "0.7";
        }

        // 启用棋盘点击
        function enableChessBoard() {
            chess.style.pointerEvents = "auto";
            chess.style.opacity = "1";
        }

        ws_hdl.onmessage = function(evt){
            //在收到room_ready之后进行房间的初始化
            //将房间信息保存起来
            var info = JSON.parse(evt.data);
            console.log(JSON.stringify(info));
            if(info.optype == "room_ready")
            {
                room_info = info;
                is_me = room_info.uid == room_info.white_id ? true : false;
                isWhite = room_info.uid == room_info.white_id;
                set_screen(is_me);
                updatePlayerInfo();
                drawPlayerColorExample();
                enableChessBoard(); // 启用棋盘点击
                initGame();
                
                // 初始化时也滚动到底部
                setTimeout(scrollToBottom, 500);
            }
            else if(info.optype == "put_chess")
            {
                //走棋操作
                console.log("put_chess" + evt.data);
                if(info.result == false)
                {
                    alert(info.reason);
                    return;
                }

                //当前走棋的用户id，与我自己的用户id相同，
                // 就是我自己走棋，走棋之后，就轮到对方了
                is_me = info.uid == room_info.uid ? false : true;
                //确定棋子颜色
                isWhite = info.uid == room_info.white_id ? true : false;

                //收到走棋消息，进行棋子绘制
                //绘制棋子
                if(info.row != -1 && info.col != -1)
                {
                    oneStep(info.col, info.row, isWhite);
                    //设置棋盘信息
                    chessBoard[info.row][info.col] = 1;
                }
                set_screen(is_me);

                //是否有胜利者
                if(info.winner == 0)
                {
                    return;
                }

                // 游戏结束，设置状态并禁用棋盘
                gameOver = true;
                disableChessBoard();

                var screen_div = document.getElementById("screen");

                if(room_info.uid == info.winner)
                {
                    screen_div.innerHTML = info.reason + " 🎉";
                    screen_div.className = "win-message";
                }
                else
                {
                    screen_div.innerHTML = "你输了! 💥";
                    screen_div.className = "lose-message";
                }

                var chess_area_div = document.getElementById("chess_area");
                
                // 检查是否已经存在返回按钮，避免重复创建
                var existingButton = document.querySelector('.back-button');
                if (!existingButton) {
                    var button_div = document.createElement("div");
                    button_div.innerHTML = "返回大厅";
                    button_div.className = "back-button";

                    button_div.onclick = function(){
                        ws_hdl.close();
                        location.replace("/game_hall.html");
                    }
                    chess_area_div.appendChild(button_div);
                }
            }
            else if(info.optype == "chat")
            {   
                //收到一条消息，判断result,结果为true,就渲染消息到界面上面
                if(info.result == false)
                {
                    alert(info.reason);
                    return;
                }

                var msg_div = document.createElement("p");
                msg_div.innerHTML = info.message;
                
                // 添加时间戳
                var time = new Date().toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit',
                    second: '2-digit'
                });
                var timeSpan = document.createElement("span");
                timeSpan.className = "message-time";
                timeSpan.textContent = time;
                
                if(info.uid == room_info.uid)
                {
                    msg_div.setAttribute("id", "self_msg");
                    msg_div.appendChild(timeSpan);
                }
                else
                {
                    msg_div.setAttribute("id", "peer_msg");
                    msg_div.appendChild(timeSpan);
                }
                
                var br_div = document.createElement("br");
                var msg_show_div = document.getElementById("chat_show");
                msg_show_div.appendChild(msg_div);
                msg_show_div.appendChild(br_div);
                document.getElementById("chat_input").value = "";
                
                // 收到新消息后自动滚动到底部
                setTimeout(scrollToBottom, 50);
            }
           
        }

        //聊天动作
        //捕捉聊天框消息
        //给发送按钮添加点击事件，点击按钮，获取到输入框消息，发送给服务器
        //当收到一条消息，给消息创建一个子标签，添加到chat_show标签中
        var cb_div = document.getElementById("chat_button");
        cb_div.onclick = function(){
            var message = document.getElementById("chat_input").value.trim();
            if (message === "") {
                return; // 空消息不发送
            }
            
            var send_msg = {
                optype: "chat",
                room_id: room_info.room_id,
                uid: room_info.uid,
                message: message
            };
            ws_hdl.send(JSON.stringify(send_msg));
            
            // 清空输入框
            document.getElementById("chat_input").value = "";
            
            // 发送后自动滚动到底部
            setTimeout(scrollToBottom, 100);
        }

        // 添加回车键发送功能
        document.getElementById("chat_input").addEventListener("keypress", function(e) {
            if (e.key === "Enter") {
                cb_div.click();
            }
        });

        // 页面加载完成后也滚动到底部
        window.addEventListener('load', function() {
            setTimeout(scrollToBottom, 1000);
        });
    </script>
</body>
</html>